<template>
    <div class="app-container">
        <el-form ref="queryForm" :inline="true">
            <!-- <el-form-item>
                <el-button type="success" @click="handleAdd">新增</el-button>
            </el-form-item> -->
            <!-- <el-button
              type="danger"
              :icon="Delete"
              @click="handleDelete"
              :disabled="multiple"
              >删除</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="queryParams.name"
              placeholder="商品名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-cascader
              v-model="queryParams.categoryId"
              placeholder="商品分类"
              :props="{ emitPath: false }"
              :options="categoryOptions"
              clearable
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery"
              >查询</el-button
            >
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item> -->
        </el-form>

        <el-table ref="dataTableRef" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange"
            @row-click="handleRowClick" border>
            <el-table-column type="selection" min-width="5%" center />
            <el-table-column type="index" label="序号" min-width="15%" center />
            <el-table-column label="请假单号" prop="leaveNo" min-width="150" />
            <el-table-column label="开始时间" prop="starDate" min-width="100" />
            <el-table-column label="请假天数" min-width="100">
                <template #default="scope">
                    <p>{{GetDateDiff(scope.row.starDate, scope.row.endDate, "day") + 1 }}天</p>
                </template>
            </el-table-column>
            <el-table-column label="申请提交时间" prop="createDate" min-width="90" />
            <el-table-column label="班级" prop="className" min-width="90" />
            <el-table-column label="申请人" prop="studentName" min-width="60" />
            <el-table-column label="状态"  min-width="100">
                <template #default="scope">
                    <p v-if="scope.row.state == 0"> 待审核</p>
                    <p v-if="scope.row.state == 1"> 审核通过</p>
                    <p v-if="scope.row.state == 2"> 审核未通过</p>
                </template>
            </el-table-column>


            <el-table-column label="操作" width="120">
                <template #default="scope">
                    <el-button type="primary" :icon="Edit" circle plain @click.stop="handleUpdate(scope.row)" />
                    <el-button type="danger" :disabled="scope.row.state == 0" :icon="Delete" circle plain
                        @click.stop="handleDelete(scope.row)" />
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 新增表单弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px">
        <el-form ref="dataFormRef" :model="formData" label-width="100px">
            <el-form-item label="假条类型" prop="workno">
                <el-radio-group v-model="formData.leaveType">
                    <el-radio :label="0">事假</el-radio>
                    <el-radio :label="1">病假</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="请假原因" prop="reason">
                <el-input v-model="formData.reason" :rows="2" type="textarea" placeholder="Please input" />
            </el-form-item>
            <el-form-item label="请假时间" prop="beginTime">
                <el-date-picker v-model="formData.starDate" placeholder="开始时间" value-format="YYYY-MM-DD" />
                ~
                <el-date-picker v-model="formData.endDate" placeholder="结束时间" value-format="YYYY-MM-DD" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 审核表单弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px">
        <el-form ref="dataFormRef"  :model="formData" label-width="100px">
            <el-form-item label="假条编号" min-width="100" >
                <span>{{formData.leaveNo}}</span>
            </el-form-item>
            <el-form-item label="假条类型" prop="workno">
                <el-radio-group :disabled="true" v-model="formData.leaveType">
                    <el-radio :label="0">事假</el-radio>
                    <el-radio :label="1">病假</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item  label="请假原因" prop="reason">
                <el-input :disabled="true" v-model="formData.reason" :rows="2" type="textarea" />
            </el-form-item>
            <el-form-item  label="请假时间" prop="beginTime">
                <el-date-picker :disabled="true" v-model="formData.starDate" placeholder="开始时间" value-format="YYYY-MM-DD" />
                ~
                <el-date-picker :disabled="true" v-model="formData.endDate" placeholder="结束时间" value-format="YYYY-MM-DD" />
               请假： <span>{{GetDateDiff(formData.starDate+"", formData.endDate+"", "day") + 1 }}天 </span>
            </el-form-item>
            <el-form-item label="申请人" min-width="100" >
                <span>{{formData.studentName}}</span>
            </el-form-item>
            <el-form-item label="申请时间" min-width="100" >
                <span>{{formData.createDate}}</span>
            </el-form-item>
            <el-form-item label="审核" min-width="100" prop="state">
                <el-radio-group v-model="formData.state">
                    <el-radio :label="1">通过</el-radio>
                    <el-radio :label="2">不通过</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="审核意见" min-width="100" prop="remarks">
                <el-input v-model="formData.remarks" :rows="2" type="textarea" />
            </el-form-item>

        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary"  @click="submitForm">提 交</el-button>
                <el-button @click="cancel">关 闭</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
    import { reactive, ref, onMounted, toRefs } from 'vue';  //导入vue的一些内置方法，v2是全部导入，v3是按需导入
    import { ElTable, ElMessage, ElMessageBox, ElForm } from 'element-plus';  //引入el的一些基础组件
    import { useRouter } from 'vue-router';  //引入路由

    import {
        Search,
        Position,
        Edit,
        Refresh,
        Delete,
        View,
    } from '@element-plus/icons-vue';  //导入图标
    //导入实体形状
    import { LeaveTicketItem, LeaveTicketFormData } from '@/types';
    import { Dialog } from '@/types/common';
    //导入api
    import { listLeaveTicketCol, getLeaveTicketColFormDetail, addLeaveTicketCol, updateLeaveTicketCol, deleteLeaveTicketCol } from '@/api/leave/leaveTicketCol';
    import { listDepartmentClass } from '@/api/system/departmentClass';
    import useStore from '@/store'

    const dataTableRef = ref(ElTable);  //暂时算是，控制表格吧
    const dataFormRef = ref(ElForm); //(模态框的控制) 属性名必须和元素的ref属性值一致
    const router = useRouter();  //实例化一个路由对象吧？
    const { user } = useStore();


    //全局用的数据
    const state = reactive({
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        //弹框
        dialog: {} as Dialog,
        //详情弹框
        dialog_detail: {} as Dialog,
        //弹出框表单
        formData: {
        } as LeaveTicketFormData,
        tableList: [] as LeaveTicketItem[],
        //班级下拉选项
        classOptions: [] as Array<any>,
    })

    const {
        loading,
        tableList,
        dialog,
        dialog_detail,
        formData,
        classOptions
    } = toRefs(state)  //从这里把数据对象衍射出去，先这样理解先

    const search = ref('')


    //列表查询的方法
    function handleQuery() {
        state.loading = true;  //打开遮罩
        listLeaveTicketCol().then(({ data }) => {
            state.tableList = data;
            state.loading = false;  //关闭遮罩
        }
        )  //初始化数据列表
    }
    //新增
    function handleAdd() {
        loadOptions();  //加载下拉选项
        state.dialog = {
            title: '新增',
            visible: true,
        };
    }
    //详情
    function handleUpdate(row: any) {
        loadOptions();  //加载下拉选项
        state.dialog = {
            title: '审核',
            visible: true,
        };
        const itemId = row.id || state.ids;
        getLeaveTicketColFormDetail(itemId).then((response) => {
            state.formData = response.data;
        });
    }
    //删除
    function handleDelete(row: any) {
        const ids = row.id || state.ids.join(',');
        ElMessageBox.confirm('是否确认删除选中的数据项?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(function () {
                return deleteLeaveTicketCol(ids);
            })
            .then(() => {
                ElMessage.success('删除成功');
                handleQuery();
            });
    }
    //行单击事件
    function handleRowClick(row: any) {
        dataTableRef.value.toggleRowSelection(row);  //单选按钮选中，应该是
    }
    //全选事件？
    function handleSelectionChange(selection: any) {
        state.ids = selection.map((item: { id: any }) => item.id);
        state.single = selection.length != 1;  //单个？
        state.multiple = !selection.length;  //多个？
    }
    //弹框表单提交
    function submitForm() {
        const roleId = state.formData.id;
        state.formData.counselorId = user.personnelId;
        if (roleId) {
            updateLeaveTicketCol(roleId, state.formData).then(() => {
                ElMessage.success('修改成功');
                cancel();  //关闭模态框
                handleQuery();  //重新查询表格数据
            });
        } else {
            addLeaveTicketCol(state.formData).then(() => {
                ElMessage.success('新增成功');
                cancel();  //关闭模态框
                handleQuery();   //重新查询表格数据
            });
        }
    }
    //关闭模态框
    function cancel() {
        dataFormRef.value.resetFields();  //将模块框中的字段重置
        state.dialog.visible = false;  //模态框置为隐藏
    }
    //关闭详情模态框
    function cancel_detail() {
        state.dialog_detail.visible = false;  //模态框置为隐藏
    }
    //加载班级下拉框选项数据
    function loadOptions() {
        listDepartmentClass().then(({ data }) => {
            state.classOptions = data;
        });
    }
    /* 
* 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时：分钟：秒 
* 其中，年月日为全格式，例如 ： 2010-10-12 01:00:00 
* 返回精度为：秒，分，小时，天
*/

    function GetDateDiff(startTime: string, endTime: string, diffType: String) {
        //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
        startTime = startTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");

        //将计算间隔类性字符转换为小写
        diffType = diffType.toLowerCase();
        var sTime = new Date(startTime);      //开始时间
        var eTime = new Date(endTime);  //结束时间
        //作为除数的数字
        var divNum = 1;
        switch (diffType) {
            case "second":
                divNum = 1000;
                break;
            case "minute":
                divNum = 1000 * 60;
                break;
            case "hour":
                divNum = 1000 * 3600;
                break;
            case "day":
                divNum = 1000 * 3600 * 24;
                break;
            default:
                break;
        }
        return (eTime.getTime() - sTime.getTime()) / divNum;
    }


    //多选删除的方法
    //   function handleDelete(row: any) {
    //   const ids = row.id || state.ids.join(',');
    //   ElMessageBox.confirm('是否确认删除选中的数据项?', '警告', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   })
    //     .then(function () {
    //       return deleteGoods(ids);
    //     })
    //     .then(() => {
    //       ElMessage.success('删除成功');
    //       handleQuery();
    //     });
    // }








    //vue的生命周期函数，这个生命周期函数，按照字面意思就是，组件安装成功之后，意思是数据呀什么的什么的，都声明好了
    //然后，我在这个组件声明好之后，给表格填入数据
    onMounted(() => {
        handleQuery();  //初始化，给表数据

    });

</script>